import { createReducer, on } from '@ngrx/store';
import { Book } from '../models/book.model';
import * as BookActions from '../actions/book.actions';

export interface bookState {
  loaded: boolean;
  loading: boolean;
  books: Book[];
}

export const initialState: bookState = {
  loaded: false,
  loading: false,
  books: []
};

export const bookReducer = createReducer(
  initialState,
  on(BookActions.addBook, (state, { book }) => {
    console.log('add state, { book }',{ ...state, books: [...state.books, book] })
    return { ...state, books: [...state.books, book] }
  }),
  on(BookActions.deleteBook, (state, { id }) => ({ ...state, books: state.books.filter(book => book.id !== id) })),
  on(BookActions.loadBooks, state => ({ ...state, loading: true })),
  // on(BookActions.loadBooksSuccess, (state, data) => {
  //   console.log('state, { books }',{loaded: true, loading: false, books: data.books})
  //   return {loaded: true, loading: false, books: data.books}
  // })
  on(BookActions.loadBooksSuccess, (state, { books }) => ({ loaded: true, loading: false, books: books.books }))
);
